package cn.edu.gues.infosystam.controller;


import cn.edu.gues.infosystam.entity.*;
import cn.edu.gues.infosystam.service.CclassService;
import cn.edu.gues.infosystam.service.ReportService;
import cn.edu.gues.infosystam.service.TaskService;
import cn.edu.gues.infosystam.service.TemplateService;
import cn.edu.gues.infosystam.utils.R;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 苏小小
 * @since 2020-06-11
 */
@Controller
@RequestMapping("/Task")
public class TaskController {

    /**
     * 班级模型
     */
    @Autowired
    private CclassService cclassService;

    /**
     * 模板
     */
    @Autowired
    private TemplateService templateService;

    /**
     * 任务
     */
    @Autowired
    private TaskService taskService;

    @Autowired
    private ReportService reportService;

    @Autowired
    private HttpSession httpSession;


    /**
     * 编辑任务界面（暂时关闭该功能） TODO: 修改任务功能
     * @param taskId 任务ID
     * @param model
     * @return
     */
    @RequestMapping("/Edit/{taskId}")
    public String editTaskView(@PathVariable String taskId, Model model) {
        Teacher teacher = getUserInfoByTeacher();
        if (teacher == null) {
            return "Login";
        }

        return "Task_Edit";
    }

    /**
     * 添加任务视图
     * @return
     */
    @RequestMapping("/Add")
    public String addTaskView(Model model){
        Teacher teacher = getUserInfoByTeacher();
        if (teacher == null) {
            return "Login";
        }

        // 构造条件
        QueryWrapper<Template> queryWrapper = new QueryWrapper<Template>();

        queryWrapper.eq("tno", 0);
        List<Template> templates = templateService.list();

        List<Cclass> colleges = cclassService.getAllCollege();

        model.addAttribute("colleges", colleges);
        model.addAttribute("templateList", templates);
        return "Task_Add";
    }

    @RequestMapping("Detail/{taskId}")
    public String detailTaskView(@PathVariable Integer taskId, @RequestParam(name = "p", defaultValue = "1") int p, Model model){
        Teacher teacher = getUserInfoByTeacher();
        if (teacher == null) {
            return "Login";
        }

        IPage<Student> taskDetail = taskService.getTaskDetail(new Page<Student>(p,50), taskId);

        QueryWrapper<Report> queryWrapper = new QueryWrapper<Report>();
        queryWrapper.eq("task_id", taskId).eq("deleted",0);
        int count = reportService.count(queryWrapper);
        System.out.println("任务："+taskDetail);

        model.addAttribute("reportTotal", count);
        model.addAttribute("taskDetail", taskDetail);
        model.addAttribute("taskId", taskId);
        return "Task_Detail";
    }

    /**
     * 任务列表界面
     * @param p 要显示的页码
     * @param search 要搜索的内容
     * @param model
     * @return
     */
    @RequestMapping("/List")
    public String listTaskView(@RequestParam(name = "p", defaultValue = "1") int p, @RequestParam(name = "s", defaultValue = "*") String search, Model model){
        Teacher teacher = getUserInfoByTeacher();
        if (teacher == null) {
            return "Login";
        }

        Page<Task> taskPage = new Page<Task>(p, 10);
        QueryWrapper<Task> queryWrapper = new QueryWrapper<Task>();
        if (teacher.getRoles() == 0)
            queryWrapper.eq("task.tno", teacher.getTno());
        if (!search.equals("*"))
            queryWrapper.eq("task_name",search);
        IPage<Task> taskList = taskService.getTaskList(taskPage, queryWrapper);

        model.addAttribute("taskPage", taskList);
        return "Task_List";
    }

    /**
     * 根据学院返回班级
     * @param college
     * @return
     */
    @ResponseBody
    @RequestMapping("class/{college}")
    public R getClassByCollege(@PathVariable String college){
        Teacher teacher = getUserInfoByTeacher();
        if (teacher == null)
            return R.error().message("你尚未登录，请先登录");

        List<Cclass> cclasses = cclassService.getClassByCollege(college);
        return R.success().data("class", cclasses);
    }

    /**
     * 保存任务
     * @param taskName 任务名称
     * @param taskTemplate 模板ID
     * @param taskStart 任务开始时间（需转换时间类型为Date）
     * @param taskEnd 任务结束时间（需转换时间类型为Date）
     * @param taskRange 任务范围（JSON字符串）
     * @return
     */
    @SneakyThrows
    @ResponseBody
    @PostMapping("Save")
    public R saveTask(String taskName, Integer taskTemplate, String taskStart, String taskEnd, String taskRange){
        Teacher teacher = getUserInfoByTeacher();
        if (teacher == null)
            return R.error().message("你尚未登录，请先登录");

        Task task = new Task();
        task.setTno(teacher.getTno());
        task.setTaskName(taskName);
        task.setTaskTemplate(taskTemplate);
        task.setTaskRange(taskRange);
        task.setTaskEnd(new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(taskEnd));
        task.setTaskStart(new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(taskStart));
        task.setTaskState(1);

        System.out.println("打印需要保存的任务："+task);
        boolean save = taskService.save(task);
        if (save)
            return R.success().data("task", task);
        else
            return R.error();
    }

    /**
     * 删除一个任务
     * @param taskId 任务ID
     * @return
     */
    @ResponseBody
    @PostMapping("Del")
    public R del(Integer taskId){
        Teacher teacher = getUserInfoByTeacher();
        if (teacher == null)
            return R.error().message("你尚未登录，请先登录");

        boolean remove = taskService.removeById(taskId);
        if (remove)
            return R.success();
        return R.error();
    }

    /**
     * 获取教师登录信息
     * @return
     */
    private Teacher getUserInfoByTeacher(){
        User userInfo = (User)httpSession.getAttribute("userInfo");
        if (userInfo == null) {
            httpSession.setAttribute("errorMsg", "请先登录");
            // 登录后可以返回的界面
            httpSession.setAttribute("historyHref","/Report/List");
            return null;
        }

        return (Teacher) userInfo.getUserInfo();
    }

}

